package com.atguigu.juc.cf;

import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author yanglin
 * @create 2023-12-28 15:52 星期四
 * description:
 */
public class FutureAPIDemo {


    /**
     * get()容易造成程序阻塞，一般建议放在程序最后
     */
    @Test
    public void testFutureApi() throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<String>( () -> {
            System.out.println(Thread.currentThread().getName() + "\t ---- come in");
            TimeUnit.SECONDS.sleep(5);
            return "task over";
        });

        Thread t1 = new Thread(futureTask, "t1");
        t1.start();
        
        System.out.println(Thread.currentThread().getName() + "\t 执行其他任务");

        //会造成程序阻塞（不过是否计算完成，都要等到结果，容易造成程序阻塞）
//        System.out.println(futureTask.get());
        
        //3秒拿不到结果就抛出异常
//        System.out.println(futureTask.get(3, TimeUnit.SECONDS));
        
        while (true){
            if (futureTask.isDone()){
                System.out.println(futureTask.get());
                break;
            }else {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println("正在处理中。。。。。");
            }
        }
    }
    
}
